import time
import itchat
from pymongo import MongoClient


def simple_reply():
    @itchat.msg_register
    def simple_reply(msg):
        if msg.get('Type', '') == 'Text':
            return 'I received: %s' % msg.get('Content', '')

    itchat.run()


def complex_reply():
    @itchat.msg_register(['Text', 'Map', 'Card', 'Note', 'Sharing'])
    def text_reply(msg):
        itchat.send('%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName'])

    @itchat.msg_register(['Picture', 'Recording', 'Attachment', 'Video'])
    def download_files(msg):
        fileDir = '%s%s' % (msg['Type'], int(time.time()))
        msg['Text'](fileDir)
        itchat.send('%s received' % msg['Type'], msg['FromUserName'])
        itchat.send('@%s@%s' % ('img' if msg['Type'] == 'Picture' else 'fil', fileDir), msg['FromUserName'])

    @itchat.msg_register('Friends')
    def add_friend(msg):
        itchat.add_friend(**msg['Text'])
        itchat.get_contract()
        itchat.send('Nice to meet you!', msg['RecommendInfo']['UserName'])

    @itchat.msg_register('Text', isGroupChat=True)
    def text_reply(msg):
        if msg['isAt']:
            key = msg['Content'].split("\u2005", 1)[1]
            if ("下单链接" in key):
                insertContent(key)
            else:
                hasRecord = False
                contents = getContent(key)
                for x in contents:
                    hasRecord=True
                    break
                if (not hasRecord):
                    itchat.send("您要找的是：" + key + ",暂时没有优惠，请稍后将为您人工查找。", msg['FromUserName'])
                else:
                    for x in contents:
                        itchat.send("您要找的是：" + key + ",结果为：\n" + x['content'], msg['FromUserName'])


    def getContent(key):
        conn = MongoClient('127.0.0.1', 27017)
        db = conn.tk
        content = db.fromwx.find({"content": {"$regex": key}})
        return content


    def insertContent(content):
        conn = MongoClient('127.0.0.1', 27017)
        db = conn.tk
        db.fromwx.insert({"content": content})


    itchat.run()

if __name__ == '__main__':
    itchat.auto_login()
    # simple_reply()
    complex_reply()
